# -*- coding: utf-8 -*-
"""
@Time : 2024/11/9 23:11
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : monitor_toutiao_user.py
"""
import requests
import time
import datetime
import logging
from urllib.parse import quote

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='monitor.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger()


def get_toutiao_user_content():
    # 头条用户“炒股的人枣庄薛城股民”的头条主页链接
    ms_token = quote(
        "dQKetsOC3tFyh0dtjbpgE5LgNUbX0fKnd4ZbRDUCW1OPacR7CKfPGNLXz8ZhJVxgS8nGy7Z7WvNji_o1O2t1LMAuTaZJuFzO2pZqi05s6LEbTcyBy2BTzg==")
    a_bogus = quote(
        "D6WhBDwDDi6kgVW25VcLfY3qVfq3Yh9u0t9bMDhqnxftCy39HMY99exoMRvv8aWjxs/gIeSjy4hbO3xprQCy8Zwf7Wsx/2CZmyh0t-P2so0j53intL6mE0hN-Jj3SFlm5XNAEOJ0y75nFYw0Aoon-vIlO6ZCcHgOEisnO76=")
    target_url = f"https://www.toutiao.com/api/pc/list/user/feed?category=profile_all&token=MS4wLjABAAAA2bH_GHAAfXMBQnWJaW4lWAJQoqFJNGqiO3IsS2fpwJrFZy1wuMg_lPHvuNspc6fo&max_behot_time=0&entrance_gid=&aid=24&app_name=toutiao_web&msToken={ms_token}&a_bogus={a_bogus}"

    header = {
        "cookie": "tt_webid=7247192801593656869;",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/131.0.0.0 Safari/537.36"
    }

    logger.info("开始请求目标头条用户的头条内容")
    try:
        r = requests.get(target_url, headers=header)
        # print(r.content)
        json_data = r.json()
        # print(json_data)
        m_toutiao_ls = json_data.get('data')
        # print(m_toutiao_ls)
        if m_toutiao_ls:
            i = m_toutiao_ls[0]
            logger.info(f"获取到的头条内容是：{i.get('content')}")
            m_toutiao_contents = [
                {"content": i.get('content'), "url": i.get("share_url"),
                 "p_time": datetime.datetime.fromtimestamp(i.get('create_time')).strftime("%Y-%m-%d %H:%M:%S"),
                 "location": i.get("publish_loc_info")}]
            # print(m_toutiao_contents)
            first_toutiao_content = m_toutiao_contents[0]
            return first_toutiao_content
        else:
            return False
    except Exception as e:
        logging.error(f"获取头条用户的过程中报错，报错信息：{e}")
        return False


if __name__ == "__main__":
    print(get_toutiao_user_content())
